package com.zhi.mbtibot.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能:
 * 作者:YukiSu
 * 日期:2024/7/21 3:53
 */
@Component
public class TokenUtil {
    @Value("${token.secretKey}")
    private String secretKey;
    /**
     * 加密token.
     */
    public String getToken(String username, String password) {
        //这个是放到负载payLoad 里面,魔法值可以使用常量类进行封装.
        return JWT
                .create()
                .withClaim("username" ,username)
                .withClaim("password", password)
                .withClaim("timeStamp", System.currentTimeMillis())
                .sign(Algorithm.HMAC256(secretKey));
    }
    /**
     * 解析token.
     * {
     * "userId": "weizhong",
     * "userRole": "ROLE_ADMIN",
     * "timeStamp": "134143214"
     * }
     */
    public Map<String, String> parseToken(String token) {
        HashMap<String, String> map = new HashMap<>();
        DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(secretKey))
                .build().verify(token);
        Claim username = decodedjwt.getClaim("username");
        Claim password = decodedjwt.getClaim("password");
        Claim timeStamp = decodedjwt.getClaim("timeStamp");
        map.put("username", username.asString());
        map.put("password", password.asString());
        map.put("timeStamp", timeStamp.asLong().toString());
        return map;
    }
}